home *** CD-ROM | disk | FTP | other *** search
/ BBS in a Box 3 / BBS in a box - Trilogy III.iso / Files / Prog / B-C / C++ FAQ Reference 1.0 / C++ FAQ Reference 1.0.rsrc / TEXT_1531.txt < prev    next >
Encoding:
Text File  |  1993-06-30  |  1.4 KB  |  61 lines

  1. Here's an example of one that will work (be sure to read the tail of this answer which details when such a scheme will *not* work):
  2.  
  3.     /****** C/C++ header file: X.h ******/
  4.     #ifdef __cplusplus    /*'__cplusplus' is #defined iff compiler is C++*/
  5.       extern "C" {
  6.     #endif
  7.  
  8.     #ifdef __STDC__
  9.       extern int c_fn(struct X*);        /* ANSI-C prototypes */
  10.       extern struct X* cplusplus_callback_fn(struct X*);
  11.     #else
  12.       extern int c_fn();            /* K&R style */
  13.       extern struct X* cplusplus_callback_fn();
  14.     #endif
  15.  
  16.     #ifdef __cplusplus
  17.       }
  18.     #endif
  19.  
  20.     #ifdef __cplusplus
  21.       class X {
  22.         int a;
  23.       public:
  24.         X();
  25.         void frob(int);
  26.       };
  27.     #endif
  28.  
  29. Then, in file 'X.C':
  30.     //X.C
  31.     #include "X.h"
  32.     X::X() : a(0) { }
  33.     void X::frob(int aa) { a = aa; }
  34.     X* cplusplus_callback_fn(X* x)
  35.     {
  36.       x->frob(123);
  37.       return x;
  38.     }
  39.  
  40. In C++ file 'main.C':
  41.     #include "X.h"
  42.     int main()
  43.     {
  44.       X x;
  45.       c_fn(&x);
  46.       return 0;
  47.     }
  48.  
  49. Finally, in a C file 'c-fn.c':
  50.     /* C source file c-fn.c */
  51.     #include "X.h"
  52.     int c_fn(struct X* x)
  53.     {
  54.       if (cplusplus_callback_fn(x))
  55.         do_one_thing();
  56.       else
  57.         do_something_else();
  58.       return something();
  59.     }
  60.  
  61. Passing ptrs to C++ objects to/from C fns will FAIL if you pass and get back something that isn't *exactly* the same pointer, such as passing a base class ptr and receiving a derived class ptr (this fails when multiple inheritance is involved, since C fails to do pointer-conversion properly).